const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 判断倒计时是否结束
 * @method timeDifference
 * @param {num} hour 时间差，单位：小时
 * @param {num} tamp 开始倒计时的时间戳
 * @return {num} 返回是否时间到
 */
const timeDifference = (hour,tamp) => {
  let timestamp = new Date().getTime();    //当前时间戳
  let td = timestamp - tamp / 3600000;     /*当前时间与保存时间的时间差*/

  if(td < hour){
    return false
  }else{
    return true
  }
}

/**
 * 倒计时
 * @method coutDown
 * @param {num} hourTm 时间差，单位：小时
 * @param {} timer  定时器
 * @return {num} 返回显示的倒计时时间
 */
const countDown = (hourTm,timer) => {
  let hm = hourTm * 60 * 60;

  if(hm == 0){
    clearTimeout(timer);
  }else{
    hm--;
    let hour = Math.floor(hm / 3600);
    let minite = Math.floor(hm / 60 % 60);
    let seconds = Math.floor(hm % 60);

    console.log(addZero(hour) + ':' + addZero(minite) + ':' + addZero(seconds));
  }

  timer = setTimeout(() => {
    clearTimeout(timer);
    countDown(hourTm,timer);
  },1000)
  
}

/**
 * 小于10前加0
 * @method addZero
 * @param {num} n 前面是否要加零的数字
 * @return 返回加0以后的结果
 */
const addZero = n => {
  return n < 10 ? '0' + n : n
}

/**
 * swiper切换到上一个
 * @method prevImg
 * @param {obj} swiper对象
 * @return swiper
 */
const prevImg = (swiper,current,isPreSlide,isNextSlide) => {
  if (current <= 0) {
    isPreSlide = false;
    isNextSlide = true
  } else {
    isPreSlide = true;
    isNextSlide = true;
  }
  swiper.current = current > 0 ? current - 1 : current;

  swiper = Object.assign({}, swiper, { isPreSlide }, { isNextSlide });

  return swiper;
}

/**
 * swiper切换到下一个
  @method  nextImg()
  @param {obj} swiper对象
  @return swiper
 */
const nextImg = swiper => {
  let current = swiper.current;
  let isPreSlide = swiper.isPreSlide;
  let isNextSlide = swiper.isNextSlide;

  if (current == swiper.videoText.length - 1 || current == swiper.videoText.length - 2) {
    isNextSlide = false;
    isPreSlide = true;
  } else {
    isNextSlide = true;
    isPreSlide = true;
  }
  swiper.current = current < (swiper.videoText.length - 1) ? current + 1 : swiper.videoText.length - 1;

  swiper = Object.assign({}, swiper, { isPreSlide }, { isNextSlide });

  return swiper;
}

module.exports = {
  formatTime: formatTime,
  timeDifference,
  countDown,
  prevImg,
  nextImg
}
